import axios from 'axios'
import { Md5 } from 'ts-md5';
import { getSign, getSignByTimestamp } from './sign.js'
import { decrypt, encrypt } from './aes';

// 接口加密
const useEncrypt = false;

const baseUrl = process.env.REACT_APP_API;
const service = axios.create({
    baseURL: baseUrl, // url = base url + request url
    timeout: 30 * 1000
    // withCredentials: true // send cookies when cross-domain requests
})

// 请求拦截器
service.interceptors.request.use((config) => {
    const { sign, timestamp } = getSign();
    if(config && config.headers) {
        config.headers.timestamp = timestamp;
        config.headers.sign = sign;
        // 启用加密
        if(useEncrypt) {
            config.data = config.data ? encrypt(JSON.stringify(config.data), sign) : null;
            config.headers.sign = Md5.hashStr(sign + (config.data ? config.data : ''));
        }
    }
    return config
},(error) => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
    console.log(response);
    const res = response.data
    if (res.code !== 0) {
        return Promise.reject(new Error(res.message || 'Error'))
    } else {
        // 启用加密
        if(useEncrypt) {
            response.data.data = JSON.parse(decrypt(response.data.data, getSignByTimestamp(response.data.timestamp)))
        }
        return response.data
    }
},(error) => {
    console.log(error.response)
    return Promise.reject(error)
})

export default service